package work.chenbo.springboot.elasticsearch.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Data
@Slf4j
public class ElasticSearchManager {

    private final RestHighLevelClient restHighLevelClient;


    /**
     * 创建索引
     * @author ChenBo
     * @date 2020/10/30
     */
    public CreateIndexResponse createIndex(String indexName) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        if(createIndexResponse.isAcknowledged()){
            log.info("创建{}索引成功",indexName);
        }else {
            log.error("创建{}索引失败",indexName);
        }
        return createIndexResponse;
    }

    /**
     * 添加映射
     * @author ChenBo
     * @date 2020/11/4
     */
    public AcknowledgedResponse  putMapping(String indexName, XContentBuilder contentBuilder) throws IOException {
        PutMappingRequest putMappingRequest = new PutMappingRequest(indexName)
                .source(contentBuilder);
        AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
        if (acknowledgedResponse.isAcknowledged()){
            log.info("索引{}添加映射成功",indexName);
        }else {
            log.error("索引{}添加映射失败",indexName);
        }
        return acknowledgedResponse;
    }

    /**
     * 添加数据
     * @author ChenBo
     * @date 2020/11/4
     */
    public IndexResponse addData(String indexName,Object object,String id) throws IOException{
        IndexRequest source = new IndexRequest()
                .index(indexName)
                .id(id)
                .source(JSON.toJSONString(object), XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(source, RequestOptions.DEFAULT);
        log.info(JSONObject.toJSONString(index));
        return index;
    }

}
